package com.easyExcel.handler;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CustomMergeStrategyNew implements RowWriteHandler {
    private int k = 0;
    private final List<String> mergeColumnNames;

    private final Integer dataSize;

    private final List<String> keys = new ArrayList<>();

    public CustomMergeStrategyNew(List<String> mergeColumnNames, Integer dataSize) {
        this.mergeColumnNames = mergeColumnNames;
        this.dataSize = dataSize;
    }

    private final Map<String, CellRangeAddress> mergedCellMap = new HashMap<>();

    private boolean isCellValueEquals(Cell cell1, Cell cell2) {
        // 比较单元格值
        return cell1.toString().equals(cell2.toString());
    }

    private void mergeRange(Sheet sheet, int firstRow, int lastRow, int cellIndex) {
        CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow, lastRow, cellIndex, cellIndex);
        sheet.addMergedRegion(cellRangeAddress);
    }

    @Override
    public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {

    }

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {

    }

        @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer rowIndex1, Boolean isHead) {
        k++;
        Sheet sheet = writeSheetHolder.getSheet();
        int rowIndex = row.getRowNum();
        if (rowIndex < 1) {
            return;
        }

        String currentCellValue = row.getCell(0).getStringCellValue();
        String prevCellValue = sheet.getRow(rowIndex - 1).getCell(0).getStringCellValue();
        boolean flag = currentCellValue == null || !currentCellValue.equals(prevCellValue);
        if(flag){
            System.out.println("我是keys===="+keys.size());
            ExecutorService executor = Executors.newFixedThreadPool(5);
            CountDownLatch count=new CountDownLatch(keys.size());
            for (String key:keys) {
                executor.submit(() -> {
                    try {
                        CellRangeAddress existingMergedCell = mergedCellMap.get(key);
                        if(existingMergedCell!=null){
                            if (existingMergedCell.getFirstRow() != existingMergedCell.getLastRow()) {
                                long startTime = System.currentTimeMillis();
                                //耗时地点
                                sheet.addMergedRegion(existingMergedCell);
                                mergedCellMap.remove(key);
                                long endTime = System.currentTimeMillis();
                                long totalTime = endTime - startTime;
                                System.out.println("Total execution time: " + totalTime/1000.0 + " seconds");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        count.countDown();
                    }

                });

            }
            try {
                count.await();
            } catch (InterruptedException e) {

            }
            keys.clear();
            executor.shutdown();
            return;
        }
        for (int i = 1; i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            Row prevRow = sheet.getRow(rowIndex - 1);

            Cell prevCell = (prevRow != null ? prevRow.getCell(i) : null);
            String oldKey = (rowIndex - 1) + "_" + i;
            String newKey = rowIndex + "_" + i;

            CellRangeAddress existingMergedCell = mergedCellMap.get(oldKey);

            if (rowIndex == 1) {
                CellRangeAddress newMergedCell = new CellRangeAddress(rowIndex, rowIndex, i, i);
                mergedCellMap.put(newKey, newMergedCell);
            }else{
                if(existingMergedCell==null) {
                    existingMergedCell = new CellRangeAddress(rowIndex-1, rowIndex-1, i, i);
                }
                    if (prevCell != null && isCellValueEquals(prevCell, cell)) {
                        mergedCellMap.remove(oldKey);
                        existingMergedCell.setLastRow(rowIndex);
                        if (rowIndex == dataSize) {
                            sheet.addMergedRegion(existingMergedCell);
                        } else {
                            mergedCellMap.put(newKey, existingMergedCell);
                            keys.add(newKey);
                        }
                    } else {
                        if (existingMergedCell.getFirstRow() != existingMergedCell.getLastRow()) {
                            sheet.addMergedRegion(existingMergedCell);
                            mergedCellMap.remove(oldKey);
                        }
                        CellRangeAddress newMergedCell = new CellRangeAddress(rowIndex, rowIndex, i, i);
                        mergedCellMap.put(newKey, newMergedCell);
                    }

            }

        }
        System.out.println("k==============="+k);
    }


}